package com.mbbb.yygh.orders.controller;

import com.mbbb.yygh.common.result.R;
import com.mbbb.yygh.enums.PaymentTypeEnum;
import com.mbbb.yygh.orders.service.PaymentInfoService;
import com.mbbb.yygh.orders.service.WeixinService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController<PaymentService> {

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @ApiOperation(value = "查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public R queryPayStatus(@PathVariable("orderId") Long orderId) {
        //1.根据订单号查询支付状态
        Map<String, String> map = weixinService.queryPayStatus(orderId,PaymentTypeEnum.WEIXIN.name());
        if (map == null)
            return R.error().message("支付失败");
        //2.如果返回成功，更新订单状态
        if ("SUCCESS".equals(map.get("trade_state"))) {
            //更新订单状态，处理支付结果
            String out_trade_no = map.get("out_trade_no");
            paymentInfoService.paySuccess(out_trade_no,PaymentTypeEnum.WEIXIN.getStatus(),map);
            return R.ok().message("支付成功");
        }
        //3.如果返回支付中，等待
        return R.ok().message("支付中");
    }

    /**
     * 生成支付二维码
     * @param orderId
     * @return
     */
    @GetMapping("/createNative/{orderId}")
    public R createNative(@PathVariable("orderId") Long orderId) {
        Map<String, Object> map = weixinService.createNativeWx(orderId);
        return R.ok().data(map);
    }
}
